package com.starleague.battletech.rules.initiative;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.starleague.StarLeagueException;
import com.starleague.battletech.game.BattletechPhase;
import com.starleague.battletech.game.IMutableBattletechGame;
import com.starleague.battletech.game.IMutableBattletechTeam;
import com.starleague.battletech.rules.AbstractPhaseState;
import com.starleague.battletech.rules.BattletechDice;
import com.starleague.battletech.rules.movement.MovementPhaseState;

@Singleton
@Named
public class InitiativePhaseState
        extends AbstractPhaseState
{
    private static final Logger log = LoggerFactory.getLogger(InitiativePhaseState.class);

    @Inject
    public InitiativePhaseState(BattletechDice dice,
                                MovementPhaseState movementPhaseState)
    {
        super(dice, BattletechPhase.INITIATIVE, movementPhaseState, BattletechPhase.NONE, BattletechPhase.END);
    }

    /**
     * Reset all Units and what not, and calculate initiative
     */
    @Override
    public void startPhase(IMutableBattletechGame game) throws StarLeagueException
    {
        super.startPhase(game);

        List<? extends IMutableBattletechTeam> initiativeTeams = Lists.newArrayList(game.getTeams());

        IMutableBattletechTeam team1 = initiativeTeams.get(0);
        IMutableBattletechTeam team2 = initiativeTeams.get(1);

        int initiativeRoll1 = rollInitiative();
        int initiativeRoll2 = rollInitiative();

        log.debug("Initiative Rolled value [{}] Team: {}", initiativeRoll1, team1);
        log.debug("Initiative Rolled value [{}] Team: {}", initiativeRoll2, team2);

        int rerollCount = 0;
        while (initiativeRoll1 == initiativeRoll2)
        {
            ++rerollCount;
            initiativeRoll1 = rollInitiative();
            initiativeRoll2 = rollInitiative();

            log.debug("Initiative Rerolled attempt [{}] value [{}] Team: {}", rerollCount, initiativeRoll1, team1);
            log.debug("Initiative Rerolled attempt [{}] value [{}] Team: {}", rerollCount, initiativeRoll2, team2);
        }

        team1.setInitiativeRoll(initiativeRoll1);
        team2.setInitiativeRoll(initiativeRoll2);

        log.info("Phase Started [{}]", game.getPhase());

        endPhase(game);
    }

    private int rollInitiative()
    {
        return this.dice.roll(2);
    }
}
